<?php
namespace forpc\controllers;

use common\models\Correct;
use common\models\Tag;
use Yii;
use common\components\Controller;
use common\components\PageView;
use common\models\Category;
use common\models\Word;
use common\models\Youdao;

/**
 * WordController
 */
class TopicController extends Controller{

    public $enableCsrfValidation = false;

    public function actionIndex(){

        $c1 = isset($_GET["c1"]) ? intval($_GET["c1"]) : 0;


        $where = " WHERE t.status=1";

        $db = Yii::$app->db;
        $sql = 'SELECT count(*) FROM {{%word_topic}} AS t'.$where;
        //echo $db->createCommand($sql)->getRawSql();exit;
        $dataCount = $db->createCommand($sql)->queryScalar();

        $perPage = 20;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $pv = new PageView($dataCount, $perPage, $currentPage);

        $sql = 'SELECT t.id, t.name, t.ids, t.pattern FROM {{%word_topic}} AS t '.
            $where." ORDER BY t.id ASC".$pv->limitSql;

        //echo $db->createCommand($sql)->getRawSql();exit;

        $topics =  $db->createCommand($sql)->queryAll();
        //echo '<pre>';
        //print_r($knowledge);exit;

        $data = [
            "topics"=> $topics,
            "pv"=>$pv,
        ];
        return $this->renderPartial('index', $data);

    }

    public function actionDetail(){

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        $db = Yii::$app->db;
        $sql = "SELECT ids FROM {{%word_topic}} WHERE id=".$id;

        $topic = $db->createCommand($sql)->queryOne();


        $ids = explode(',',$topic["ids"]);

        $where = " WHERE TRUE";
        $con1 = (count($ids) > 0) ? " AND w.id IN(".$topic["ids"].")" : "";
        $where = $where.$con1;


        $db = Yii::$app->db;

        $sql = 'SELECT w.id, w.cid, t.name AS cname, c2.name AS cname2, w.word, w.ipa_en, w.ipa_us, w.trans, w.correct_write, w.correct_time, f.id AS f_id FROM {{%english}} AS w '.
            'LEFT JOIN {{%knowledge_cate}} AS t ON w.c1=t.id '.
            'LEFT JOIN {{%knowledge_cate}} AS c2 ON w.c2=c2.id '.
            'LEFT JOIN {{%user_practices}} AS f ON w.id=f.id '.
            $where;

        //echo $db->createCommand($sql)->getRawSql();exit;

        $words =  $db->createCommand($sql)->queryAll();
        //echo '<pre>';
        //print_r($knowledge);exit;

        $data = [
            "words"=> $words,
            "mobile"=>1,
        ];

        return $this->renderPartial('detail', $data);
    }

    public function actionEdit(){

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        $pre_word = isset($_GET["word"]) ? addslashes($_GET["word"]) : "";//准备添加的单词

        $categorys = Category::getData();
        $treeData = Category::getTree($categorys);

        $db = Yii::$app->db;
        $sql = "SELECT `c1`, `c2`, `c3`, `id`,`cid`, `word`, `ipa_en`, `ipa_us`, `trans` FROM {{%english}} WHERE id=$id";

        $knowledge = $db->createCommand($sql)->queryOne();

        $data = [
            "id" => $id,
            "pre_word" => $pre_word,
            "treeData" => $treeData,
            "knowledge" => $knowledge,
        ];
        return $this->renderPartial('edit', $data);
    }

    public function actionAsyncEdit(){
        $id = isset($_POST["id"]) ? intval($_POST["id"]) : 0;
        $c1 = isset($_POST["c1"]) ? intval($_POST["c1"]) : 0;
        $c2 = isset($_POST["c2"]) ? intval($_POST["c2"]) : 0;
        $c3 = isset($_POST["c3"]) ? intval($_POST["c3"]) : 0;
        $cid = isset($_POST["cid"]) ? intval($_POST["cid"]) : 0;
        $word = isset($_POST["word"]) ? addslashes($_POST["word"]) : "";
        $ipa_en = isset($_POST["ipa_en"]) ? addslashes($_POST["ipa_en"]) : "";
        $ipa_us = isset($_POST["ipa_us"]) ? addslashes($_POST["ipa_us"]) : "";
        $trans = isset($_POST["trans"]) ? addslashes($_POST["trans"]) : "";

        $data = [
            'c1' => $c1,
            'c2' => $c2,
            'c3' => $c3,
            'cid' => $cid,
            'word' => $word,
            'ipa_en' => $ipa_en,
            'ipa_us' => $ipa_us,
            'trans' => $trans,
            'update_time' => time(),
        ];

        $db = Yii::$app->db;
        if(empty($id)){
            $id =  $db->createCommand("SELECT `id` FROM {{%english}} WHERE BINARY word='".$word."'")->queryScalar();
            if($id > 0){
                exit(json_encode(["code"=>-2, "info"=>"单词".$word."已经存在", "id"=>$id], JSON_UNESCAPED_UNICODE));
            }

            $line = $db->createCommand()->insert('{{%english}}', $data)->execute();
            if($line == 1){
                $id = $db->getLastInsertID();
                exit(json_encode(["code"=>1, "info"=>"添加成功", "id"=>$id], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"添加失败"], JSON_UNESCAPED_UNICODE));
            }
        }else{
            $line = $db->createCommand()->update('{{%english}}', $data, 'id='.$id)->execute();
            if($line == 1){
                exit(json_encode(["code"=>1, "info"=>"编辑成功"], JSON_UNESCAPED_UNICODE));
            }else{
                exit(json_encode(["code"=>-3, "info"=>"编辑失败"], JSON_UNESCAPED_UNICODE));
            }
        }

    }

    public function actionInsertFromYoudao(){

        $word = isset($_GET["word"]) ? addslashes($_GET["word"]) : "";

        if(empty($word)){
            exit(json_encode(["code"=>-1, "info"=>"请输入单词"], JSON_UNESCAPED_UNICODE));
        }

        $text = Youdao::getText($word);
        //echo $text;

        if(empty($text)){
            exit(json_encode(["code"=>-1, "info"=>"抓取不到内容"], JSON_UNESCAPED_UNICODE));
        }

        $data = [];
        $data["word"] = Youdao::getWord($text);
        $data["ipa"] = Youdao::getIPA($text);
        $data["trans"] = Youdao::getChineseTrans($text);

//        echo '<pre>';
//        print_r($data);

        exit(json_encode(["code"=>1, "info"=>"成功", "data"=>$data], JSON_UNESCAPED_UNICODE));

    }


    /**
     * 说、写、正确
     * @throws \yii\db\Exception
     */
    public function actionAsyncCorrectWrite(){
        header("Content-Type;text/html; charset=utf-8");

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        if(empty($id)){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
        }

        $db = Yii::$app->db;
        $word = $db->createCommand("SELECT correct_write, `correct_time` FROM {{%english}} WHERE id=$id")->queryOne();

        $correct_write = $word["correct_write"];
        $correct_time = $word["correct_time"];

        $curtime = time();

        $locktime = \common\components\Common::getLocktime($correct_write);

        if($correct_time + $locktime > $curtime){
            exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过".($locktime/3600)."小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
        }

        $sql = "UPDATE {{%english}} SET correct_time='".time()."', `correct_write`=`correct_write`+1 WHERE id=$id";

        $line = $db->createCommand($sql)->execute();

        if($line == 1){
            exit(json_encode(["code"=>1, "info"=>"成功"], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(["code"=>-3, "info"=>"失败"], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * Demote
     * @throws \yii\db\Exception
     */
    public function actionAsyncDemoteWrite(){
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        if(empty($id)){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
        }

        $db = Yii::$app->db;
        $word = $db->createCommand("SELECT correct_write, `correct_time` FROM {{%english}} WHERE id=$id")->queryOne();

        $correct_write = $word["correct_write"];

        if($correct_write == 0){
            exit(json_encode(["code"=>-2, "info"=>"已经最低，不能再降"], JSON_UNESCAPED_UNICODE));
        }

        $sql = "UPDATE {{%english}} SET `correct_write`=`correct_write`-1 WHERE id=$id";
        $line = $db->createCommand($sql)->execute();

        if($line == 1){
            exit(json_encode(["code"=>1, "info"=>"成功"], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(["code"=>-3, "info"=>"失败"], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 直接毕业
     * @throws \yii\db\Exception
     */
    public function actionAsyncGraduate(){
        header("Content-Type;text/html; charset=utf-8");

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        if(empty($id)){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
        }

        $db = Yii::$app->db;

        $word = $db->createCommand("SELECT correct_write, `correct_read`, `correct_time` FROM {{%english}} WHERE id=$id")->queryOne();

        if(empty($word)){
            exit(json_encode(["code"=>-2, "info"=>"单词不存在"], JSON_UNESCAPED_UNICODE));
        }

        $correct_write = intval($word["correct_write"]);
        $correct_read = intval($word["correct_read"]);
        $correct_time = $word["correct_time"];

        $curtime = time();

        $locktime = \common\components\Common::getLocktime($correct_write);

        if($correct_time + $locktime > $curtime){
            exit(json_encode(["code"=>-2, "info"=>"距离上次操作不超过".($locktime/3600)."小时，请稍后再试"], JSON_UNESCAPED_UNICODE));
        }

        $data = [
            'correct_write' => ($correct_write>15) ? new \yii\db\Expression('correct_write+1') : 16,
            'correct_read' => ($correct_read>15) ? new \yii\db\Expression('correct_read+1') : 16,
            'correct_time' => time(),
            'update_time' => time(),
        ];

        $line = $db->createCommand()->update('{{%english}}', $data, 'id='.$id)->execute();

        if($line == 1){
            exit(json_encode(["code"=>1, "info"=>"成功"], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(["code"=>-3, "info"=>"失败"], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 收藏
     * @throws \yii\db\Exception
     */
    public function actionFavorite(){

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        if(empty($id) || $id <= 0){
            exit(json_encode(["code"=>-1, "info"=>"缺少参数知识ID"], JSON_UNESCAPED_UNICODE));
        }

        $db = Yii::$app->db;

        if($db->createCommand("SELECT count(*) FROM {{%user_practices}} WHERE id=$id")->queryScalar() > 0){
            exit(json_encode(["code"=>-2, "info"=>"已收藏过"], JSON_UNESCAPED_UNICODE));
        }

        $lastOrder = \common\models\Favorite::getLastOrder();
        $data = [
            'id' => $id,
            'create_time' => time(),
            'update_time' => time(),
            'displayorder' => $lastOrder+1,
        ];
        $line = $db->createCommand()->insert('{{%user_practices}}', $data)->execute();
        if($line == 1){
            exit(json_encode(["code"=>1, "info"=>"插入成功"], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(["code"=>-3, "info"=>"插入失败"], JSON_UNESCAPED_UNICODE));
        }

    }

    public function actionFavoriteAllUnstudyWord(){
        $db = Yii::$app->db;
        $sql = "SELECT w.id FROM en_word AS w WHERE w.id NOT IN(SELECT id FROM en_user_practices) AND w.correct_write<16";

        $ids = $db->createCommand($sql)->queryColumn();

        echo '<pre>';


        shuffle($ids);
        print_r($ids);

        $lastOrder = \common\models\Favorite::getLastOrder();
        foreach($ids as $i => $id){

            $data = [
                'id' => $id,
                'create_time' => time(),
                'update_time' => time(),
                'displayorder' => $lastOrder+1+intval($i),
            ];
            $line = $db->createCommand()->insert('{{%user_practices}}', $data)->execute();
        }

        echo "完成，收藏单词".count($ids)."个";

        exit;

    }


}
